package cn.jsony.user.service.impl;

import cn.jsony.basic.config.BusinessException;
import cn.jsony.basic.constant.VerifyCodeConstants;
import cn.jsony.basic.util.Md5Utils;
import cn.jsony.basic.util.StrUtils;
import cn.jsony.org.domain.Employee;
import cn.jsony.org.domain.Shop;
import cn.jsony.user.domain.Logininfo;
import cn.jsony.user.domain.User;
import cn.jsony.user.dto.EmailDto;
import cn.jsony.user.dto.UserDto;
import cn.jsony.user.mapper.LogininfoMapper;
import cn.jsony.user.mapper.UserMapper;
import cn.jsony.user.service.IUserService;
import cn.jsony.basic.service.impl.BaseServiceImpl;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;


    @Autowired
    private JavaMailSender javaMailSender;
    @Override
    public void phoneRegister(UserDto userDto) {



        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String confirmPwd = userDto.getConfirmPwd();
        String pwd = userDto.getPwd();
        //1.验证非空
        if(phone==null ||phoneCode==null ||confirmPwd==null ||pwd==null  ){
            throw new BusinessException("数据不能为空");
        }

        //2.密码一致
        if(!confirmPwd.equals(pwd)){
            throw new BusinessException("两次输入的密码不一致");
        }

        //3.验证码是否过期,是否正确
        //yzmobj=验证码:时间戳
        Object yzmobj = redisTemplate.opsForValue()
                .get(VerifyCodeConstants.REGISTER_CODE_PREFIX + phone);
        if(!yzmobj.toString().split(":")[0].equals(phoneCode)){
            throw new BusinessException("验证码不一致");
        }
        if(yzmobj==null){
            throw new BusinessException("验证码已过期");
        }


        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        //保存t_logininfo,获取自增长ID
        logininfoMapper.save(logininfo);
        //保存t_user
        Long logininfoId = logininfo.getId();
        user.setLogininfo_id(logininfoId);
        userMapper.save(user);
    }

    //邮箱注册
    @Override
    public void emailRegister(EmailDto emailDto) throws MessagingException {
        User user = userMapper.loadByEmail(emailDto.getEmail());
        String password = emailDto.getPassword();
        String email = emailDto.getEmail();
        String comfirmPassword = emailDto.getComfirmPassword();

        //1.验证前端的用户名和密码非空
        if (password ==null || email==null) {
            throw new BusinessException("用户名和密码不能为空");

        }

        //2.验证是否注册过
        if(user!=null){
            throw new BusinessException("该账号已经注册了");
        }

        //3.密码是否一致
        if(!comfirmPassword.equals(password)){
            throw new BusinessException("密码不一致");
        }

        //4.发送邮件:注册
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类‘
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送方
        helper.setFrom("1104829900@qq.com");
        //主题
        helper.setSubject("宠物乐园");
        //设置内容
        helper.setText("<h1>宠物乐园</h1>"
                + "<a href='http://localhost:8080/user/register/Successfully/1'>点击链接完成邮箱注册</a>",true);
        //设置收件人
        helper.setTo(emailDto.getEmail());
        //发送
        javaMailSender.send(mimeMessage);



        User userEmail = emailDto2User(emailDto);
        Logininfo logininfo = userEmail2Logininfo(userEmail);
        //保存t_logininfo,获取自增长ID
        logininfoMapper.save(logininfo);
        //保存t_user
        Long logininfoId = logininfo.getId();
        userEmail.setLogininfo_id(logininfoId);
        userEmail.setCreatetime(new Date());
        userMapper.save(userEmail);

    }

    //邮件激活的重写方法
    @Override
    public void emailPassr(Long id) {

        User userById = userMapper.loadById(id);
        userById.setState(1);
        userMapper.update(userById);
    }


    private User emailDto2User(EmailDto emailDto) {
        User userEmail = new User();
        userEmail.setUsername(emailDto.getEmail());
        String password = emailDto.getPassword();
        String salt = StrUtils.getComplexRandomString(32);
        //获取加盐后的密码
        String md5 = Md5Utils.encrypByMd5(password + salt);

        userEmail.setPassword(md5);
        userEmail.setSalt(salt);
        return userEmail;
    }

    private Logininfo userEmail2Logininfo(User userEmail) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(userEmail,logininfo);
        logininfo.setType(1);
        return logininfo;
    }


    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());

        String salt = StrUtils.getComplexRandomString(32);

        //获取加密之后的密码,密码加盐
        String md5 = Md5Utils.encrypByMd5(userDto.getPwd() + salt);

        user.setSalt(salt);
        user.setPassword(md5);
        return user;
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        //当前用户type 是1
        logininfo.setType(1);
        return logininfo;

    }


    @Override
    @Transactional
    public void add(User user) {
        //增加和修改,对盐值和密码进行加密,为了保护信息
        String salt = StrUtils.getComplexRandomString(6);

        //获取加密之后的密码,密码加盐
        String md5 = Md5Utils.encrypByMd5(user.getPassword() + salt);

        user.setSalt(salt);
        user.setPassword(md5);

        //把增加后的user对象转换成Loginfo
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        user.setLogininfo_id(logininfo.getId());
        super.add(user);
    }

    @Override
    @Transactional
    public void del(Long id) {
        User user = userMapper.loadById(id);
        Long logininfo_id = user.getLogininfo_id();
        logininfoMapper.remove(logininfo_id);
        super.del(id);
    }

    @Override
    @Transactional
    public void update(User user) {
        //增加和修改,对盐值和密码进行加密,为了保护信息
        String salt = StrUtils.getComplexRandomString(6);

        //获取加密之后的密码,密码加盐
        String md5 = Md5Utils.encrypByMd5(user.getPassword() + salt);

        user.setSalt(salt);
        user.setPassword(md5);

        //把修改后的user对象转换成Loginfo
        Logininfo logininfo = user2Logininfo(user);
        //log_infoid==Logininfo的id
        Long logininfo_id = userMapper.loadById(user.getId()).getLogininfo_id();
        logininfo.setId(logininfo_id);

        logininfoMapper.update(logininfo);

        super.update(user);
    }
}
